<?php

defined('BASEPATH') OR exit('No direct script access allowed');

define('TYPE_ID', 1);
define('TYPE_TEXT', 2);
define('TYPE_CHECKBOX', 3);
define('TYPE_RADIO', 4);
define('TYPE_SELECT', 5);
define('TYPE_DATE', 6);
define('TYPE_DATETIME', 7);
define('TYPE_NUMBER', 8);
define('TYPE_IMAGE', 9);
define('TYPE_CURRENCY', 10);
define('TYPE_SORT', 11);
define('TYPE_COLOR', 12);
define('TYPE_WEIGHT', 13);
define('TYPE_URL', 14);
define('TYPE_TEXTAREA', 15);


define('BTN_OK', 1);
define('BTN_CANCEL', 2);
define('BTN_SKIP', 4);


class DojoForm {
    
    public $_data;
    public $models = array();
    public $config = array();
    protected $_ci;


    function __construct($config = array()) {
        $this->_ci = & get_instance();
        if (!empty($config)) {
            $this->initialize($config);
        }
    }

    function initialize($config = array()) {
        foreach ($config as $key => $val) {
            $this->{'_' . $key} = $val;
        }
    }
    
    function add_model_fields($model, $fields, $form_id=0) {
        $this->models[$model] = array(
            'fields'=>$fields, 
            'form_id'=>$form_id,
            'dojo_fields' => $this->_ci->$model->dojo_fields
        );         
    }
    
    function add_grid_fields($model, $fields, $grid_id) {
        
    }
    
//    function field_store_json($field_name, $lang=FALSE) {
//        $store = $this->dojo_fields[$field_name]['store'];
//        $this->db->from($store['from']);
//        foreach ($store['join'] as $table => $join_on) {
//            $this->db->join($table, $join_on);
//        }
//        $this->db->select($store['fields']);
//        $query = $this->db->get()->result_array();
//        return "{ identifier: 'id', items:" . json_encode($query) . "}";        
//    }
    
    function grid_render($grid_id=0, $grid_config=array()) {
        $this->_data['models'] = $this->models;
        $this->_data['grid_id'] = $grid_id;        
        
        return $this->_ci->load->view('backend/dojo_grid',$this->_data,TRUE);
    }
    
    function render($form_id=0, $form_config=array()) {
        
        $this->_data['models'] = $this->models;
        $this->_data['form_id'] = $form_id;        
        
        $default_cfg = array (
            'left_width' => '200',
            'form_title' => 'FORM '.$form_id.' HEADING',
            'button' => BTN_OK|BTN_CANCEL,
            'action' => current_url()
        );
        
        foreach ($form_config as $key => $value) {
            $default_cfg[$key] = $value;
        }
        
        $this->_data['form_config'] = $default_cfg;        
        
        return $this->_ci->load->view('backend/dojo_fields',$this->_data,TRUE);
    }
    
    static public function getFieldsValue($form_id, $fields) {
        $CI = & get_instance();
        foreach ($fields as $f) {
            $out[$f] = $CI->input->post($f . '_' . $form_id);
        }
        return $out;
    }    
 
}